import time,json
import requests
from requests.exceptions import RequestException
from lxml import etree
from bs4 import BeautifulSoup
from pyquery import PyQuery as pq 


def getPage(url):
    '''爬取指定url地址的信息'''
    try:
        #请求头信息
        headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}
        #执行爬取
        res = requests.get(url)
        #判断并返回结果
        if res.status_code == 200:
            return res.text
        else:
            return None
    except RequestException:
        return None

def parsePage(content):
    '''解析爬取网页中的内容，并返回结果'''
    #print(content)
    #==================使用Xpath解析===========================
    
    #初始化，返回根节点对象
    html = etree.HTML(content)
    #解析网页中<tr class='item'>...</div>信息
    items = html.xpath("//tr[@class='item']")
    #遍历并解析每本书的具体信息
    #print(len(items))
    for item in items:
        yield{
            'title':item.xpath(".//td/div/a/text()")[0],
            'image':item.xpath(".//img[@width='90']/@src")[0],
            'author':item.xpath(".//p[@class='pl']/text()")[0],
            'score':item.xpath(".//span[@class='rating_nums']/text()")[0],
        }
    ''' 
    #==================使用BeautifulSoup解析===========================
    #初始化，创建解析器
    soup = BeautifulSoup(content,"lxml")
    #解析网页中<tr class='item'>...</div>信息
    items = soup.find_all(name="tr",attrs={"class":"item"})
    #遍历并解析每本书的具体信息
    #print(len(items))
    for item in items:
        yield{
            'title':item.select('div.pl2 a')[0].get_text(),
            'image':item.find(name="img",attrs={'width':'90'}).attrs['src'],
            'author':item.select("p.pl")[0].get_text(),
            'score':item.find(name = 'span',attrs={'class':"rating_nums"}).string,
        }

    
    #==================使用pyquery解析===========================
    #初始化，返回Pyquery对象
    doc = pq(content)
    #解析网页中<tr class='item'>...</div>信息
    items = doc("table")
    #遍历并解析每本书的具体信息
    #print(len(items))
    for item in items.items():
        yield{
            'title':item.find('div.pl2 a').text(),
            'image':item.find('a.nbg img').attr('src'),
            'author':item.find("p.pl").text(),
            'score':item.find("span.rating_nums").text(),
        }
    '''
    
def writeFile(content):
    '''爬取指定url地址的信息'''
    with open("./result.txt",'a',encoding='utf-8') as f:
        f.write(json.dumps(content,ensure_ascii=False)+"\n")
    

def main(offset):
    '''主程序函数，负责调度执行爬取处理'''
    url = 'https://book.douban.com/top250?start=' + str(offset)
    html = getPage(url) #执行爬取
    if html:
        for item in parsePage(html): #执行解析并遍历
            #print(item)
            writeFile(item) #执行些操作

    pass

#判断当前执行是否为主程序，并遍历调度主函数来爬取信息
if __name__ == '__main__':
    #main(0)
    for i in range(10):
        main(offset=i*25)
        time.sleep(1)
